<script lang="ts" setup>
  import { ref, reactive, onMounted, defineProps,defineEmits,withDefaults } from 'vue';
  import { useRouter } from 'vue-router';
  import { Page } from '@vben/common-ui';
  import { message, Input, Button, Dropdown, Menu, MenuItem, Space } from 'ant-design-vue';
  import { useVbenVxeGrid } from '#/adapter/vxe-table';
  import { getPageList, getLayout, getPageHeaders, deleteByIds } from '#/api';
  import { MenuAction } from '.'
  import type {ActionProp, GTableConfig} from '../../utils/declar';

  // 定义 props 并设置默认值
  const props = withDefaults(defineProps<{
    config: GTableConfig;
  }>(), {
    config: () => ({
      className: 'default-table', // 默认类名
      isTree: false,              // 默认不是树形表格
      queryData: undefined,       // 默认没有查询条件
      actionApiGet: true,         // 默认通过 API 获取数据
      customType: "replace",      //操作按钮客制化类型
      customTopActions:[],
      customRightActions:[]
    }),
  });

  console.log("props.hhhhhhhh",props.config.actionApiGet)
  const emit = defineEmits(["cellClick"]);
  const className = props.config.className
  const value = ref<string>('');  // 搜索框的值
  const conditions = reactive(new Map<string, any>());
  const sortConditions = reactive(new Map<string, any>());
  const columnsChecked = reactive(new Map<string, any>());
  const checkboxData = reactive(new Set<number>());

  convertParamsToConditions()

  const gridOptions = reactive({
    filterMultiple: false,
    showOverflow: true,
    showHeaderOverflow: true,
    showFooterOverflow: true,
    scrollX: {
      enabled: true,
      gt: 0
    },
    height: 570,
    exportConfig: { type: "", mode: "all" },
    toolbarConfig: {
      code: "reload",
      slots: { buttons: 'toolbar_buttons', tools: 'right_buttons' },
      print: true,
      custom: true,
      export: true,
      import: true,
      refresh: { queryMethod: resetFiltersAndSort },
      zoom: true,
      search: true,
    },
    columns: [],
    data: [],
    pagerConfig: {
      pageSizes: [10, 20, 50, 100],
      enabled: true,
      border: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      layouts: ['PrevJump', 'PrevPage', 'Jump', 'PageCount', 'NextPage', 'NextJump', 'Sizes', 'Total'],
    },
    sortConfig: {
      remote: true,
      multiple: true,
      chronological:true,
      orders: ['asc', 'desc', 'null'],
    },
    seqConfig: {
      seqMethod: ({ rowIndex }) => (gridOptions.pagerConfig.currentPage - 1) * gridOptions.pagerConfig.pageSize + rowIndex + 1,
    },
    checkboxConfig: { reserve: true },
    border: true,
    stripe: true,
    scrollY: {
      enabled: true,  // 启用水平滚动
      oSize:10
    },
  });

  const treeConfig = {
    transform:true,
    seqMode:'increasing',
    showLine:true
  }

  if(props.config.isTree){
    gridOptions.treeConfig = treeConfig
  }

  const [Grid, gridApi] = useVbenVxeGrid({
    gridEvents: {
      pageChange: onPageChange,
      filterChange: handleFilterChange,
      sortChange: handleSortChange,
      toolbarToolClick: openToFormPage,
      checkboxChange: handleCheckboxChange,
      checkboxAll: handleCheckboxAll,
      cellClick: cellClick
    },
    gridOptions,
    gridMethod: { sort: () => {
        console.log("sdssssss")
      }, clearSort: (fieldOrColumn) => {} },
  });

  const router = useRouter();

  function resetFiltersAndSort() {
    conditions.clear();
    convertParamsToConditions();
    sortConditions.clear();
    columnsChecked.clear();
    resetColumnFilters();
    getPage();
  }

  function resetColumnFilters() {
    gridOptions.columns.forEach((item) => {
      if (item.filters) {
        item.filters.forEach((filter) => {
          filter.checked = null;
          filter.data = null;
        });
      }
    });

    gridApi.setGridOptions({columns:gridOptions.columns});
  }

  async function getPage() {
    try {
      gridApi.setLoading(true);
      const res = await getPageList({
        typeName: className,
        searchKey: value.value,
        pageIndex: gridOptions.pagerConfig.currentPage,
        pageSize: gridOptions.pagerConfig.pageSize,
        conditions: [...conditions.values(), ...sortConditions.values()],
      });
      const { records, total, sizes } = res;
      const data = [];
      records.forEach(item=>{
        const attrObj = item.attrList.reduce((acc, attr) => {
          if(attr.attrName === "parentId"){
            acc["parentId"] = attr.value;
          }else {
            acc[attr.attrName] = attr.displayName;
          }
          return acc;
        }, {} as Record<string, any>);
        data.push(attrObj);
      })
      gridOptions.data = data;
      gridApi.setGridOptions({
        data: data,
        pagerConfig: { pageSize: sizes, total },
      });
    } catch (error) {
      console.error("加载数据失败:", error);
      message.error("加载数据失败");
    } finally {
      gridApi.setLoading(false);
    }
  }

  function handleFilterChange({ column, field, values, datas, filterList, $event }) {
    if (datas.length === 0) {
      conditions.delete(field);
    } else {
      conditions.set(field, { attr: field, condition: "LIKE", value: datas[0] });
    }
    columnsChecked.set(field, { checked: datas.length > 0, value: datas[0] });
    updateFiltersInColumns();
    getPage();
  }

  function updateFiltersInColumns() {
    gridOptions.columns.forEach((item) => {
      const filterValue = columnsChecked.get(item.field);
      if (filterValue) {
        item.filters?.forEach((filter) => {
          filter.checked = filterValue.checked;
          filter.data = filterValue.value;
        });
      }
    });
    gridApi.setGridOptions({ columns: gridOptions.columns });
  }

  function handleSortChange({ column, field, order, sortBy, sortList, $event }) {
    if (order === null) {
      sortConditions.delete(field);
    } else {
      sortConditions.set(field, { attr: field, condition: "ORDER_BY", value: order });
    }
    gridApi.setGridOptions({sortConfig:{
        defaultSort: { field, order }
      }});
    getPage();
  }

  function handleCheckboxChange({ checked, row }: any) {
    checked ? checkboxData.add(row.pid) : checkboxData.delete(row.pid);
  }

  function handleCheckboxAll({ checked }: any) {
    if (checked) {
      gridOptions.data.forEach((item) => checkboxData.add(item.pid));
    } else {
      checkboxData.clear();
    }
  }

  function cellClick({ row, rowIndex, $rowIndex, column, columnIndex}){
    emit("cellClick", { row, column });
  }



  async function getHeader() {
    try {
      const res = await getPageHeaders(className);

      // 预处理 columns，减少多次遍历
      const columnMap = Object.fromEntries(res.columns.map(item => [item.field, item]));

      // 设置 cellRender
      if (columnMap.icon) {
        columnMap.icon.cellRender = { name: "IconRender" };
      }

      if (columnMap.code) {
        columnMap.code.cellRender = { name: "LinkRender" };
      } else if (columnMap.name) {
        columnMap.name.cellRender = { name: "LinkRender" };
      }

      // 生成表头 columns
      const columns = [
        { type: "checkbox", width: 50 },
        { title: "序号", type: "seq", width: 60 },
        ...res.columns,
        createActionColumn(),
      ];

      // 更新表格配置
      gridOptions.columns = columns;
      gridApi.setGridOptions({ columns });
    } catch (error) {
      console.error("加载数据失败:", error);
      message.error("加载数据失败");
    }
  }

  function createActionColumn() {
    return {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 120,
    };
  }

  function openToFormPage(operate: string) {
      router.push({ path: '/form', query: {type: operate,className:className} });
  }

  function onPageChange({ type, currentPage, pageSize, $event }) {
    gridOptions.pagerConfig.currentPage = currentPage;
    gridOptions.pagerConfig.pageSize = pageSize;
    gridApi.setGridOptions({ pagerConfig: { currentPage, pageSize } });
    getPage();
  }

  function search() {
    let temp = gridOptions.pagerConfig.currentPage;
    gridOptions.pagerConfig.currentPage=1
    getPage();
    gridOptions.pagerConfig.currentPage=temp;
  }

  function doRightAction() {
    // 删除后刷新表格
    getPage();
  }


  // 遍历 params 并将其转换为条件
  function convertParamsToConditions() {
    if( props.config.queryData!= undefined && props.config.queryData.length>0){
      props.config.queryData.forEach((param) => {
        conditions.set(param.field, param);
      });
    }
  }

  onMounted(() => {
    getHeader();
    getPage();
  });
</script>

<template>
    <Grid :key="gridOptions.pagerConfig.currentPage"  class="relative h-full">
      <template #action="{ row }">
      <MenuAction :rowData="row" @doAction="doRightAction" actionType="right" :actionApiGet="props.config.actionApiGet"/>
    </template>
      <template #toolbar_buttons>
        <Input v-model:value="value" placeholder="请输入关键字" style="width: 30%" @change="search" @pressEnter="search">
          <template #prefix>
            <span class="icon-[lucide--search]"></span>
          </template>
        </Input>
      </template>
      <template #right_buttons>
        <Space>
          <Button type="primary" @click="openToFormPage('CREATE')">
            <a style="display: inline-flex; align-items: center">
              <span class="icon-[icons8--plus]" style="margin-left: -4px;margin-right: 4px; font-size: 20px"></span>
              新增
            </a>
          </Button>
          <Button type="primary" danger>
            <MenuAction :rowData="checkboxData"
                        @doAction="doRightAction"
                        actionType="top"
                        v-bind="props.config"
         />
          </Button>
        </Space>
      </template>
    </Grid>
</template>
